<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------


/**
 * 会员收货地址类
 * @package  module/base/customer
 * @author   allen.qiang
 * @version 1.0
 */

class custDeliver {

    /**
     * 查询会员收货地址
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchCustDeliver( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //省ID
        if (isset($arg_array['provinceid']) && is_numeric($arg_array['provinceid'])) {
            $sql .= ' AND provinceid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['provinceid'];
        }

        //收货地址城市id
        if (isset($arg_array['cityid']) && is_numeric($arg_array['cityid'])) {
            $sql .= ' AND cityid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityid'];
        }

        //区ID
        if (isset($arg_array['countyid']) && is_numeric($arg_array['countyid'])) {
            $sql .= ' AND countyid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['countyid'];
        }

        //收货地址ID
        if (isset($arg_array['deliverID']) && is_numeric($arg_array['deliverID'])) {
            $sql .= ' AND deliverID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['deliverID'];
        }

        //收货地址
        if (isset($arg_array['address']) && !empty($arg_array['address'])) {
            $sql .= ' AND address LIKE ? ';
            $params_type .= 's';
            $params_array[] = '%' . encrypt_paramD($arg_array['address']) . '%';
        }

        //收货地址(不是模糊查询)
        if (isset($arg_array['precise_address']) && !empty($arg_array['precise_address'])) {
            $sql .= ' AND address = ? ';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['precise_address']);
        }

        //省名
        if (isset($arg_array['provinceName']) && !empty($arg_array['provinceName'])) {
            $sql .= ' AND provinceName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . encrypt_paramD($arg_array['provinceName']) . '%';
        }

        //市名
        if (isset($arg_array['cityName']) && !empty($arg_array['cityName'])) {
            $sql .= ' AND cityName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . encrypt_paramD($arg_array['cityName']) . '%';
        }

        //区名
        if (isset($arg_array['countyName']) && !empty($arg_array['countyName'])) {
            $sql .= ' AND countyName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . encrypt_paramD($arg_array['countyName']) . '%';
        }

        //收货人姓名
        if (isset($arg_array['custName']) && !empty($arg_array['custName'])) {
            $sql .= ' AND custName = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['custName']);
        }

        //手机号码
        if (isset($arg_array['mobile']) && !empty($arg_array['mobile'])) {
            $sql .= ' AND mobile = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['mobile']);
        }

        //电话号码
        if (isset($arg_array['phone']) && !empty($arg_array['phone'])) {
            $sql .= ' AND phone = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['phone']);
        }

        //精确度
        if (isset($arg_array['precise']) && in_array($arg_array['precise'], array('0', '1', '2'))) {
            $sql .= ' AND precise = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['precise'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_deliver ' . $sql;

                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);

                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM cust_deliver ' . $sql;

            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            $item_array = array();

            foreach($temp_item_array as &$item) {

                //站点自提 add by allen.qiang 2015-06-29
                if($item->type == 2){

                    //配送站地址
                    $distributionInfo = $G_SHOP->DBCA->stmt_query('SELECT provinceName,cityName,countyName,provinceid,cityid,countyid,address FROM sys_distribution WHERE distribution_id = '.$item->distribution_id);

                    //更新配送地址
                    $item_array[] = array(
                        'pcustID' => $item->pcustID,
                        'deliverID' => $item->deliverID,
                        'provinceName' => $distributionInfo[0]->provinceName,
                        'cityName' => $distributionInfo[0]->cityName,
                        'countyName' => $distributionInfo[0]->countyName,
                        'provinceid' => $distributionInfo[0]->provinceid,
                        'cityid' => $distributionInfo[0]->cityid,
                        'countyid' => $distributionInfo[0]->countyid,
                        'address' => $distributionInfo[0]->address,
                        'custName' => decryptD($item->custName),
                        'postalCode'=>$item->postalCode,
                        'mobile' => decryptD($item->mobile),
                        'phone' => decryptD($item->phone),
                        'longitude' => $item->longitude,
                        'latitude' => $item->latitude,
                        'precise' => $item->precise,
                        'type' => $item->type,
                        'distribution_id' => $item->distribution_id,
                        'is_default' => $item->is_default
                    );

                }else{

                    $item_array[] = array(
                        'pcustID' => $item->pcustID,
                        'deliverID' => $item->deliverID,
                        'provinceName' => $item->provinceName,
                        'cityName' => $item->cityName,
                        'countyName' => $item->countyName,
                        'provinceid' => $item->provinceid,
                        'cityid' => $item->cityid,
                        'countyid' => $item->countyid,
                        'address' => decryptD($item->address),
                        'custName' => decryptD($item->custName),
                        'postalCode'=>$item->postalCode,
                        'mobile' => decryptD($item->mobile),
                        'phone' => decryptD($item->phone),
                        'longitude' => $item->longitude,
                        'latitude' => $item->latitude,
                        'precise' => $item->precise,
                        'type' => $item->type,
                        'distribution_id' => $item->distribution_id,
                        'is_default' => $item->is_default
                    );

                }

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询会员收货地址详情
     * @param int $deliverID 收货地址ID
     * @param int $pcustID 会员号
     * @return null
     */
    public function searchCustDeliverDetail( $deliverID, $pcustID ) {

        if (!isset($pcustID) || empty($pcustID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!isset($deliverID) || empty($deliverID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        $args_array = array(
            'deliverID' => $deliverID,
            'pcustID' => $pcustID,
        );
        $deliver_array = $this->searchCustDeliver( $args_array );
        if ($deliver_array) {
            return $deliver_array[0];
        } else {
            return null;
        }

    }

    /**
     * 保存或修改会员地址信息
     * @param $arg_array
     * @param bool $check_map_area 检查配送区域是否存在
     * @return array
     * @throws Exception
     */
    public function editCustDeliver( $arg_array, $check_map_area = false ) {

        global $G_SHOP;
        if (!isset($arg_array['pcustID'], $arg_array['creator'], $arg_array['custName'], $arg_array['provinceid'], $arg_array['cityid'], $arg_array['countyid'],$arg_array['address'], $arg_array['mobile']))
            return array( 'code' => 400, 'message' => '参数错误' );

        if(mb_strlen($arg_array['custName']) > 15){
            return array( 'code' => 400, 'message' => '收货人长度不能超过15个汉字或英文字母' );
        }

        if (!isset($arg_array['phone']))
            $arg_array['phone'] = null;

        if (!empty($arg_array['deliverID']) && !is_numeric($arg_array['deliverID'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if(isset($arg_array['is_default']) && !is_numeric($arg_array['is_default'])){
            return array( 'code' => 400, 'message' => '设置默认地址参数错误' );
        }

        if (empty($arg_array['custName']))
            return array( 'code' => 400, 'message' => '收货人不能为空，请填写' );

        if (!is_numeric($arg_array['provinceid']) || !is_numeric($arg_array['cityid']) || $arg_array['provinceid'] <= 0  || $arg_array['cityid'] <= 0)
            return array( 'code' => 400, 'message' => '请选择省市区' );

        if (empty($arg_array['address']))
            return array( 'code' => 400, 'message' => '收货地址不能为空，请填写' );

        if (empty($arg_array['mobile']) && empty($arg_array['phone']))
            return array( 'code' => 400, 'message' => '“手机”和“固定电话”至少填写一项' );

        if (isset($arg_array['postalCode']) && !empty($arg_array['postalCode'])) {
            if (strlen($arg_array['postalCode']) != 6 || !is_numeric($arg_array['postalCode'])) {
                return array( 'code' => 400, 'message' => '请输入正确的邮编');
            }
        } else {
            $arg_array['postalCode'] = null;
        }

        if(isset($arg_array['type']) && !empty($arg_array['type'])){

            if(!isset($arg_array['distribution_id']) || empty($arg_array['distribution_id'])){
                return array( 'code' => 400, 'message' => '请选择配送站');
            }
        }


        if (!empty($arg_array['mobile']) && !is_mobile($arg_array['mobile']))
            return array( 'code' => 400, 'message' => '手机号码填写错误，格式：18612345678，请重新填写' );

        if (!empty($arg_array['phone']) && !is_phone($arg_array['phone']))
            return array( 'code' => 400, 'message' => '固定电话填写错误，格式：021-60745701，请重新填写' );

        if (!isset($arg_array['deliverID']) || !is_numeric($arg_array['deliverID']))
            $arg_array['deliverID'] = 0;

        if(!isset($arg_array['phone']) || empty($arg_array['phone']))
            $arg_array['phone'] = '';

       
        try {

            $G_SHOP->DBCA->beginTransaction();
            //查询省份信息
            $province_obj = new entity('sys_region');
            $province_obj->id = $arg_array['provinceid'];
            $province_obj->region_level = 1;
            if (!$G_SHOP->DBCA->fetch($province_obj))
                throw new Exception('省份信息没有找到', 404);

            //查询市区信息
            $city_obj = new entity('sys_region');
            $city_obj->id = $arg_array['cityid'];
            $city_obj->region_level = 2;
            if (!$G_SHOP->DBCA->fetch($city_obj))
                throw new Exception('市区信息没有找到', 404);

            $county_obj = new entity('sys_region');
            $county_obj->id = $arg_array['countyid'];
            $county_obj->region_level = 3;
            $G_SHOP->DBCA->fetch($county_obj);
//                throw new Exception('地区信息没有找到', 404);

            //add allen.qiang 20141202 详细地址是否在当前城市站判断---start
//            $city_array = get_city(); //城市列表
//            foreach($city_array as &$city_check) {
//                if($city_check["name"] != $city_obj->name && $city_check["front_display"]==1){
//                    $check_city=array();
//                    $check_city[]=$city_check["name"];
//                    $check_city[]=mb_substr($city_check["name"], 0, 2, 'utf-8');
//                    if(in_array(mb_substr($arg_array['address'], 0, 2, 'utf-8'), $check_city) || in_array(mb_substr($arg_array['address'], 0, 3, 'utf-8'), $check_city))
//                        throw new Exception('地址不在'.mb_substr($city_obj->name, 0, 2, 'utf-8').'，请重新选择，或切换至'.mb_substr($city_check["name"], 0, 2, 'utf-8').'站重新下单', 404);
//                }
//            }
            //add allen.qiang 20141202 详细地址是否在当前城市站判断---end

//del allen.qiang 20141202 详细地址是否在当前城市站判断---start
            //详细地址是否在当前城市站判断
          /*  $check_sh = array( '上海市');
            $check_hz = array( '杭州市');

            if(in_array($city_obj->name, $check_sh)){
                if(in_array(mb_substr($arg_array['address'], 0, 3, 'utf-8'), $check_hz))
                    throw new Exception('地址不在上海，请重新选择，或切换至杭州站重新下单', 404);

            }elseif(in_array($city_obj->name, $check_hz)){
                if(in_array(mb_substr($arg_array['address'], 0, 3, 'utf-8'), $check_sh))
                    throw new Exception('地址不在杭州，请重新选择，或切换至上海站重新下单', 404);
            }*/
//del allen.qiang 20141202 详细地址是否在当前城市站判断---start

            //检查会员信息
            $cust_obj = new entity('cust_master');
            $cust_obj->pcustID = $arg_array['pcustID'];
            if (!$G_SHOP->DBCA->fetch($cust_obj))
                throw new Exception('会员信息没有找到', 404);

            $check_address = $province_obj->name . $city_obj->name . $county_obj->name . $arg_array['address'] . $arg_array['custName'] . $arg_array['mobile'] . $arg_array['phone'];

            //保存或更新会员地址信息
            $deliver_obj = new entity('cust_deliver');
            $deliver_obj->pcustID = $arg_array['pcustID'];

            if ($arg_array['deliverID'] > 0) {

                //检测相同收货地址
                $search_sql = 'SELECT * FROM cust_deliver WHERE pcustID = ? AND check_address = ? AND deliverID != ?';
                $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, 'isi',$arg_array['pcustID'], encryptD($check_address), $arg_array['deliverID']);
                if ($temp_item_array)
                    throw new Exception('会员收货地址不能重复', 404);

                //更改deliverID为最早一个的id

                $deliver_obj->deliverID = $arg_array['deliverID'];
                if (!$G_SHOP->DBCA->fetch($deliver_obj))
                    throw new Exception('收货地址没有找到', 404);

                $deliver_obj->editor  = $arg_array['creator'];
                $deliver_obj->check_address = encryptD($check_address);

            } else {
                if(encryptD($check_address)){
                    $deliver_obj->check_address = encryptD($check_address);
                    if($G_SHOP->DBCA->fetch($deliver_obj)){
                        throw new Exception('会员收货地址不能重复',404);
                    }
                }

                $deliver_obj->creator = $arg_array['creator'];
                $deliver_obj->deliverID = generate_seqno('seqno_custdeliver');

                if(!isset($arg_array['is_default'])){
                    $arg_array['is_default'] = 0;
                }
            }

            $alter_array = "";

            if ($arg_array['deliverID'] > 0) {
                $alter_array .= $arg_array['deliverID']."<br/>";
                $alter_array .= '地址修改：'."<br/>";
            } else {
                $alter_array .= '地址新增：'."<br/>";
            }

            if ($deliver_obj->provinceName != $province_obj->name) {
                $alter_array .= '    省份：' . $deliver_obj->provinceName . ' => ' .  $province_obj->name."<br/>";
            }
            if ($deliver_obj->cityName != $city_obj->name) {
                $alter_array .= '    市区：' . $deliver_obj->provinceName . ' => ' .  $province_obj->name."<br/>";
            }
            if ($deliver_obj->countyName != $county_obj->name) {
                $alter_array .= '    地区：' . $deliver_obj->provinceName . ' => ' .  $province_obj->name."<br/>";
            }
            if (decryptD($deliver_obj->address) != $arg_array['address']) {
                $alter_array .= '    地址：' . decryptD($deliver_obj->address) . ' => ' .  $arg_array['address']."<br/>";
            }
            if (decryptD($deliver_obj->custName) != $arg_array['custName']) {
                $alter_array .= '    收货人：' . decryptD($deliver_obj->custName) . ' => ' .  $arg_array['custName']."<br/>";
            }

            //设置默认地址
            if(isset($arg_array['is_default'])){

                if($arg_array['is_default'] == 1){

                    $G_SHOP->DBCA->stmt_query('UPDATE cust_deliver SET is_default = 0 WHERE pcustID=?', 'i', $arg_array['pcustID']);
                    $deliver_obj->is_default = 1;

                }else{
                    $deliver_obj->is_default = 0;
                }

            }

            //根据地址匹配经纬度
            $address_detail = $province_obj->name . $city_obj->name . $county_obj->name . $arg_array['address'];
            //add allen.qiang 20141210 FUN-BK-0041-G7地址库平台接入---start
            if(G_LATITUDE_COUNTY==0){ //地址经纬度不开启区匹配
                $address_detail = $province_obj->name.$city_obj->name.$arg_array['address'];
            }
            //add allen.qiang 20141210 FUN-BK-0041-G7地址库平台接入---end
            $coordinate_array = get_address_coordinate( $address_detail );
            if ($coordinate_array['match'] == 0) {
                throw new Exception('收货地址无法匹配,建议输入地址格式：***路***弄***号***室', 404);
            }

            if ($check_map_area) {
                $map_area_array = get_map_area($coordinate_array['longitude'], $coordinate_array['latitude'], $city_obj->id, 1);
                if ($map_area_array['areaID'] == 0) {
                    throw new Exception('超出配送范围，请重新选择地址，或选择自提点自提', 404);
                }
            }

            //根据经纬度
            $deliver_obj->provinceName = $province_obj->name;
            $deliver_obj->cityName = $city_obj->name;
            $deliver_obj->countyName = $county_obj->name;
            $deliver_obj->provinceid = $province_obj->id;
            $deliver_obj->cityid = $city_obj->id;
            $deliver_obj->countyid = $county_obj->id;
            $deliver_obj->address = encryptD(convertVar($arg_array['address']));
            $deliver_obj->custName = encryptD(convertVar($arg_array['custName']));
            $deliver_obj->postalCode = $arg_array['postalCode'];
            $deliver_obj->mobile = encryptD($arg_array['mobile']);
            $deliver_obj->phone = encryptD($arg_array['phone']);
            $deliver_obj->longitude = $coordinate_array['longitude'];
            $deliver_obj->latitude = $coordinate_array['latitude'];
            $deliver_obj->precise = $coordinate_array['precise'];
            $deliver_obj->type = isset($arg_array['type'])?$arg_array['type'] : 1;
            $deliver_obj->distribution_id = isset($arg_array['distribution_id'])?$arg_array['distribution_id']:0;
            //add 20141230 sunqiang FUN-BK-0045-地址识别来源标记 start
            $deliver_obj->locator = $coordinate_array['locator'];
            //add 20141230 sunqiang FUN-BK-0045-地址识别来源标记 end

            if (isset($alter_array[0])) {

                $G_SHOP->DBCA->save($deliver_obj);

                quanli_require('module/base/customer/logHandler.class.php');

                //日志类
                $logHandler = new logHandler($G_SHOP->DBCA);

                $logArr['logItem'] = $arg_array['pcustID'];
                $logArr['logCategoryID'] = 9;
                $logArr['operator'] = $arg_array['creator'];
                $logArr['extend_1'] = $alter_array;
                $saveResult = $logHandler->saveLogInfo( $logArr );

                if( $saveResult['code'] != 200 )
                    throw new Exception($saveResult['message'], $saveResult['code']);

            }

            $deliver_array = array(
                'pcustID' => $deliver_obj->pcustID,
                'deliverID' => $deliver_obj->deliverID,
                'provinceName' => $deliver_obj->provinceName,
                'cityName' => $deliver_obj->cityName,
                'countyName' => $deliver_obj->countyName,
                'provinceid' => $deliver_obj->provinceid,
                'cityid' => $deliver_obj->cityid,
                'countyid' => $deliver_obj->countyid,
                'address' => $arg_array['address'],
                'postalCode' => $arg_array['postalCode'],
                'custName' => $arg_array['custName'],
                'mobile' => $arg_array['mobile'],
                'phone' => $arg_array['phone'],
                'type' => $deliver_obj->type,
                'longitude' => $deliver_obj->longitude,
                'latitude' => $deliver_obj->latitude,
                'distribution_id' => $deliver_obj->distribution_id,
                //add allen.qiang 2015-03-05 MK-FUN-AC-45-WAP端迷你拿破仑活动---start
                'precise' => $deliver_obj->precise,
                //add allen.qiang 2015-03-05 MK-FUN-AC-45-WAP端迷你拿破仑活动---end
                'is_default' => $deliver_obj->is_default
            );

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '保存成功', 'data' => $deliver_array );

        } catch (Exception $e) {
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }



    /**
     * 保存或修改会员地址信息
     * @param $arg_array
     * @param bool $check_map_area 检查配送区域是否存在
     * @return array
     * @throws Exception
     */
    public function editCustDeliver111( $arg_array, $check_map_area = false ) {

        global $G_SHOP;

        if (!isset($arg_array['pcustID'], $arg_array['creator'], $arg_array['custName'], $arg_array['provinceid'], $arg_array['cityid'], $arg_array['countyid'],$arg_array['address'], $arg_array['mobile']))
            return array( 'code' => 400, 'message' => '参数错误' );

        if(mb_strlen($arg_array['custName']) > 15){
            //return array( 'code' => 400, 'message' => '收货人长度不能超过15个汉字或英文字母' );
        }

        if (!isset($arg_array['phone']))
            $arg_array['phone'] = null;

        if (!empty($arg_array['deliverID']) && !is_numeric($arg_array['deliverID'])) {
           // return array( 'code' => 400, 'message' => '参数错误' );
        }

        if(isset($arg_array['is_default']) && !is_numeric($arg_array['is_default'])){
           // return array( 'code' => 400, 'message' => '设置默认地址参数错误' );
        }

        if (empty($arg_array['custName']))
           // return array( 'code' => 400, 'message' => '收货人不能为空，请填写' );

        if (!is_numeric($arg_array['provinceid']) || !is_numeric($arg_array['cityid']) || $arg_array['provinceid'] <= 0  || $arg_array['cityid'] <= 0)
            return array( 'code' => 400, 'message' => '请选择省市区' );

        if (empty($arg_array['address']))
            //return array( 'code' => 400, 'message' => '收货地址不能为空，请填写' );

        if (empty($arg_array['mobile']) && empty($arg_array['phone']))
            return array( 'code' => 400, 'message' => '“手机”和“固定电话”至少填写一项' );

        if (isset($arg_array['postalCode']) && !empty($arg_array['postalCode'])) {
            if (strlen($arg_array['postalCode']) != 6 || !is_numeric($arg_array['postalCode'])) {
               // return array( 'code' => 400, 'message' => '请输入正确的邮编');
            }
        } else {
            $arg_array['postalCode'] = null;
        }

        if(isset($arg_array['type']) && !empty($arg_array['type'])){

            if(!isset($arg_array['distribution_id']) || empty($arg_array['distribution_id'])){
                return array( 'code' => 400, 'message' => '请选择配送站');
            }
        }


//        if (!empty($arg_array['mobile']) && !is_mobile($arg_array['mobile']))
//            return array( 'code' => 400, 'message' => '手机号码填写错误，格式：18612345678，请重新填写' );

//        if (!empty($arg_array['phone']) && !is_phone($arg_array['phone']))
//            return array( 'code' => 400, 'message' => '固定电话填写错误，格式：021-60745701，请重新填写' );

        if (!isset($arg_array['deliverID']) || !is_numeric($arg_array['deliverID']))
            $arg_array['deliverID'] = 0;

        if(!isset($arg_array['phone']) || empty($arg_array['phone']))
            $arg_array['phone'] = '';

        try {

            $G_SHOP->DBCA->beginTransaction();
            //查询省份信息
            $province_obj = new entity('sys_region');
            $province_obj->id = $arg_array['provinceid'];
            $province_obj->region_level = 1;
            if (!$G_SHOP->DBCA->fetch($province_obj))
                throw new Exception('省份信息没有找到', 404);

            //查询市区信息
            $city_obj = new entity('sys_region');
            $city_obj->id = $arg_array['cityid'];
            $city_obj->region_level = 2;
            if (!$G_SHOP->DBCA->fetch($city_obj))
                throw new Exception('市区信息没有找到', 404);

            $county_obj = new entity('sys_region');
            $county_obj->id = $arg_array['countyid'];
            $county_obj->region_level = 3;
            if (!$G_SHOP->DBCA->fetch($county_obj))
                throw new Exception('countyid not fount->'.$arg_array['countyid'], 404);

            //根据地址匹配经纬度
            $address_detail = $province_obj->name . $city_obj->name . $county_obj->name . $arg_array['address'];
            //add allen.qiang 20141210 FUN-BK-0041-G7地址库平台接入---start
            if(G_LATITUDE_COUNTY==0){ //地址经纬度不开启区匹配
                $address_detail = $province_obj->name.$city_obj->name.$arg_array['address'];
            }
            //add allen.qiang 20141210 FUN-BK-0041-G7地址库平台接入---end
            $coordinate_array = get_address_coordinate( $address_detail );

            if ($coordinate_array['match'] == 0) {
                throw new Exception('收货地址无法匹配,建议输入地址格式：***路***弄***号***室', 404);
            }

            if ($check_map_area) {
                $map_area_array = get_map_area($coordinate_array['longitude'], $coordinate_array['latitude'], $city_obj->id, 1);
                if ($map_area_array['areaID'] == 0) {
                    throw new Exception('超出配送范围，请重新选择地址，或选择自提点自提', 404);
                }
            }

            //根据经纬度
            $deliver_obj->provinceName = $province_obj->name;
            $deliver_obj->cityName = $city_obj->name;
            $deliver_obj->countyName = $county_obj->name;
            $deliver_obj->provinceid = $province_obj->id;
            $deliver_obj->cityid = $city_obj->id;
            $deliver_obj->countyid = $county_obj->id;
            $deliver_obj->address = encryptD(convertVar($arg_array['address']));
            $deliver_obj->custName = encryptD(convertVar($arg_array['custName']));
            $deliver_obj->postalCode = $arg_array['postalCode'];
            $deliver_obj->mobile = encryptD($arg_array['mobile']);
            $deliver_obj->phone = encryptD($arg_array['phone']);
            $deliver_obj->longitude = $coordinate_array['longitude'];
            $deliver_obj->latitude = $coordinate_array['latitude'];
            $deliver_obj->precise = $coordinate_array['precise'];
            $deliver_obj->type = isset($arg_array['type'])?$arg_array['type'] : 1;
            $deliver_obj->distribution_id = isset($arg_array['distribution_id'])?$arg_array['distribution_id']:0;
            //add 20141230 sunqiang FUN-BK-0045-地址识别来源标记 start
            $deliver_obj->locator = $coordinate_array['locator'];
            //add 20141230 sunqiang FUN-BK-0045-地址识别来源标记 end

            $deliver_array = array(
                'pcustID' => $deliver_obj->pcustID,
                'deliverID' => $deliver_obj->deliverID,
                'provinceName' => $deliver_obj->provinceName,
                'cityName' => $deliver_obj->cityName,
                'countyName' => $deliver_obj->countyName,
                'provinceid' => $deliver_obj->provinceid,
                'cityid' => $deliver_obj->cityid,
                'countyid' => $deliver_obj->countyid,
                'address' => $arg_array['address'],
                'postalCode' => $arg_array['postalCode'],
                'custName' => $arg_array['custName'],
                'mobile' => $arg_array['mobile'],
                'phone' => $arg_array['phone'],
                'type' => $deliver_obj->type,
                'longitude' => $deliver_obj->longitude,
                'latitude' => $deliver_obj->latitude,
                'distribution_id' => $deliver_obj->distribution_id,
                //add allen.qiang 2015-03-05 MK-FUN-AC-45-WAP端迷你拿破仑活动---start
                'precise' => $deliver_obj->precise,
                //add allen.qiang 2015-03-05 MK-FUN-AC-45-WAP端迷你拿破仑活动---end
                'is_default' => $deliver_obj->is_default
            );

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '保存成功', 'data' => $deliver_array );

        } catch (Exception $e) {
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 删除会员收货地址
     * @param int $pcustID    会员号
     * @param int $deliverID  收货地址ID
     * @return array
     * @throws Exception
     */
    public function delCustDeliver($pcustID, $deliverID) {

        global $G_SHOP;

        if (!isset($pcustID, $deliverID) || !is_numeric($pcustID) || !is_numeric($deliverID))
            return array( 'code' => 400, 'message' => '缺少参数' );

        try {

            //查询会员收货地址信息
            $deliver_obj = new entity('cust_deliver');
            $deliver_obj->pcustID = $pcustID;
            $deliver_obj->deliverID = $deliverID;
            if (!$G_SHOP->DBCA->fetch($deliver_obj))
                throw new Exception('收货地址信息没有找到', 404);

            //删除会员收货地址
            $G_SHOP->DBCA->delete($deliver_obj);

            return array( 'code' => 200, 'message' => '收货地址删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 新增/修改地址
     * @param array $arg_array 地址参数数组
     * @return array
     */
    public function editAddress( $arg_array ) {

        global $G_SHOP;

        if (!isset( $arg_array['deliverID'], $arg_array['longitude'], $arg_array['latitude'])
            || !quanli_is_int($arg_array['deliverID']) || !is_numeric($arg_array['longitude']) || !is_numeric($arg_array['latitude'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $deliver_obj = new entity('cust_deliver');
            $deliver_obj->deliverID = $arg_array['deliverID'];
            if (!$G_SHOP->DBCA->fetch($deliver_obj)) {
                throw new Exception('地址信息没有找到', 404);
            }
            $deliver_obj->longitude = $arg_array['longitude'];
            $deliver_obj->latitude = $arg_array['latitude'];
            $deliver_obj->precise = 1;
            //add 20141230 sunqiang FUN-BK-0045-地址识别来源标记 start
            $deliver_obj->locator = 'custom';
            //add 20141230 sunqiang FUN-BK-0045-地址识别来源标记 end
            $G_SHOP->DBCA->save($deliver_obj);

            return array( 'code' => 200, 'message' => '地址修改成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 收货地址坐标更新
     * @param int $deliverID 地址id
     * @param array $coordinate_array 经纬度数组
     * @return array
     */
    public function updateAddressCoordinate( $deliverID, $coordinate_array ) {

        global $G_SHOP;

        try {

            $deliver_obj = new entity('cust_deliver');
            $deliver_obj->deliverID = $deliverID;
            if (!$G_SHOP->DBCA->fetch($deliver_obj)) {
                throw new Exception('地址信息没有找到', 404);
            }
            $deliver_obj->longitude = $coordinate_array['longitude'];
            $deliver_obj->latitude = $coordinate_array['latitude'];
            $deliver_obj->precise = $coordinate_array['precise'];
            $G_SHOP->DBCA->save($deliver_obj);

            return array( 'code' => 200, 'message' => '收货地址坐标更新成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询会员默认收货地址
     * @param int $pcustID 会员ID
     * @return array
     */
    public function getDefaultAddress( $pcustID ){

        global $G_SHOP;

        $deliver_obj = new entity('cust_deliver');
        $deliver_obj->pcustID = $pcustID;
        $deliver_obj->is_default = 1;

        if (!$G_SHOP->DBCA->fetch($deliver_obj))
            return null;

        return $deliver_obj->deliverID;

    }

    /**
     *
     * 查询最早添加的收货地址
     * @param int $pcustID 会员ID
     * @return array
     * @author allen.qiang
     */
    public function getBoldAddress( $pcustID ){

        //判断会员号存不存在
        if (!isset($pcustID) || empty($pcustID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        $args_array = array(
            'pcustID' => $pcustID,
            'sortname' => 'createTime',
            'sortorder' => 'ASC',
            'page' => '1',
            'rp' => '1'
        );
        $deliver_array = $this->searchCustDeliver( $args_array );
        if ($deliver_array) {
               //$item_array['province_id'] = $deliver_array[0]['provinceid']; 
               //$item_array['city_id'] = $deliver_array[0]['cityid']; 
               //$item_array['country_id'] = $deliver_array[0]['countyid']; 
               $item_array['deliverID']=$deliver_array[0]['deliverID']; 
            return $item_array;
        } else {
            return null;
        }

    }

}